﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Grove.Tools.XmlImport {
	using System.Text.RegularExpressions;
	using System.Xml;

	public class Program {

		public static void Main(string[] args) {
			args = new[] { @"C:\Users\GodLesZ\Desktop\Projects\Games\MTG\MagicGrove\docs\mtg-cards-br.xml" };
			if (args.Length == 0) {
				DisplayUsage();
				return;
			}

			foreach (var filename in args) {
				XmlDocument doc = new XmlDocument();
				try {
					doc.Load(filename);
					if (doc.DocumentElement == null || doc.DocumentElement.Name != "mtg_carddatabase")
					{
						throw new Exception("Unexpected root element, expected \"mtg_carddatabase\".");
					}
				} catch (Exception ex) {
					Console.WriteLine("Failed to open xml file: " + filename);
					Console.WriteLine("-----------------------------------------------------");
					Console.WriteLine(ex.ToString());
					continue;
				}

				var cardsNode = doc.DocumentElement.FirstChild;
				if (cardsNode.Name != "cards") {
					Console.WriteLine("No cards found in xml file: " + filename);
					Console.WriteLine("-----------------------------------------------------");
					continue;
				}

				foreach (var card in cardsNode.ChildNodes.Cast<XmlNode>().Where(card => card.Name == "card"))
				{
					CreateCsharpFile(card);
				}

			}
		}

		private static void CreateCsharpFile(XmlNode card)
		{
			var cardFilename = card["name"].Value;
			// Strip anything
			cardFilename = Regex.Replace(cardFilename, "[^a-z0-9 ]", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
			// Space was left out to join every part with first char uppercase
			cardFilename = string.Join("", 
				cardFilename
					.Split(' ')
					.Select(
						p => p.Trim().Substring(0, 1).ToUpperInvariant() + p.Trim().Substring(1).ToLowerInvariant()
					)
				);

			// Create card based on his type
		}

		private static void DisplayUsage() {
			Console.WriteLine("-----------------------------------------------------");
			Console.WriteLine("MagicGrove - Xml import tool");
			Console.WriteLine("-----------------------------------------------------");
			Console.WriteLine("Usage: Just drag a valid XML file on it.");
			Console.WriteLine();
			Console.WriteLine("Press any key to exit.");
			Console.Read();
		}
	}

}
